package com.solo.controller;

import com.solo.UserService.UserService;
import com.solo.entity.User;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/*
 * FileName: LoginController.java
 * Description: 处理登录相关请求
 * Author:   woolflighthouse@163.com
 * Date:     2025-11-23 7:26
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    /**
     * 根路径重定向到登录页
     */
    // @GetMapping("/")
    // public String root() {
    //     logger.debug("根路径访问，重定向到登录页");
    //     return "redirect:/login";
    // }

    /**
     * 跳转到登录页面
     */
    @GetMapping("/login")
    public String toLogin() {
        logger.debug("访问登录页面");
        return "login";
    }

    /**
     * 处理登录表单提交
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        Model model,
                        HttpSession session) {
        logger.info("用户尝试登录: {}", username);

        try {
            // 调用服务层验证用户身份
            User user = userService.login(username, password);

            if (user != null) {
                // 登录成功，将用户信息存入session
                session.setAttribute("loginUser", user);
                logger.info("用户登录成功: {}", username);
                return "redirect:/home"; // 重定向到首页
            } else {
                // 登录失败，返回错误信息
                model.addAttribute("errorMsg", "用户名或密码错误");
                logger.warn("用户登录失败: {}", username);
                return "login";
            }
        } catch (Exception e) {
            logger.error("登录过程发生异常", e);
            model.addAttribute("errorMsg", "系统异常，请稍后重试");
            return "login";
        }
    }

    /**
     * 处理退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            logger.info("用户退出登录: {}", user.getUsername());
        }
        session.invalidate(); // 销毁session
        return "redirect:/login"; // 重定向到登录页
    }
}
